package org.fxkj.cloud.uaa.service.security;

import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.fxkj.cloud.uaa.service.security.model.token.JwtAuthenticationToken;
import org.fxkj.cloud.uaa.service.security.model.token.JwtTokenFactory;
import org.fxkj.cloud.uaa.service.security.model.token.RawAccessJwtToken;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

/**
 * <p>Description: </p>
 *
 * @author Wei, Wu
 * @create 2024/11/18 17:07
 */
@Component
@RequiredArgsConstructor
public class WAuthenticationProvider implements AuthenticationProvider {
    private final JwtTokenFactory tokenFactory;
    private final UserService userService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        RawAccessJwtToken rawAccessToken = (RawAccessJwtToken) authentication.getCredentials();
        SecurityUser securityUser = authenticate(rawAccessToken.getToken());
        return new JwtAuthenticationToken(securityUser);
    }

    public SecurityUser authenticate(String accessToken) throws AuthenticationException {
        if (StringUtils.isEmpty(accessToken)) {
            throw new BadCredentialsException("Token is invalid");
        }
        SecurityUser securityUser = tokenFactory.parseAccessJwtToken(accessToken);
        SecurityUser user = userService.loadUserByUsername(securityUser.getWxOpenid());
        if (null == user) {
            throw new RuntimeException("用户不存在");
        }
        if (user.isEnabled()) {
            return user;
        }
        throw new RuntimeException("用户不可用");
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return JwtAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
